package cc.eddic.practice.concurrency.impl;

import cc.eddic.practice.concurrency.CDNLogItem;
import cc.eddic.practice.concurrency.LogItem;
import lombok.val;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Optional;
import java.util.regex.Pattern;

public class CDNLogParserCxm {

    private static final Pattern PATTERN_LOG_LINE = Pattern.compile("(?<clientIP>.+) (?<hitMiss>.+) (?<responseTime>\\d+) \\[(?<timeZone>.+)] \"(?<method>\\w+) (?<url>.+) (?<protocol>\\S+?)\" (?<statusCode>\\d+) (?<trafficSize>\\d+) \"(?<referer>.*?)\" \"(?<userAgent>.*)\"", Pattern.UNICODE_CHARACTER_CLASS | Pattern.DOTALL);


    public Optional<CDNLogItem> parse(String line) {
        String clientIP = null,hitMiss = null,responseTime = null,timeZone = null,method = null,url = null,protocol = null,statusCode = null,trafficSize = null,referer = null,userAgent = null;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);
        val m = PATTERN_LOG_LINE.matcher(line);
        if(m.matches()){
            clientIP=m.group("clientIP");
            hitMiss=m.group("hitMiss");
            responseTime=m.group("responseTime");
            timeZone=m.group("timeZone");
            method=m.group("method");
            url=m.group("url");
            protocol=m.group("protocol");
            statusCode=m.group("statusCode");
            trafficSize=m.group("trafficSize");
            referer=m.group("referer");
            userAgent=m.group("userAgent");
        }
        return Optional.of(new CDNLogItem(clientIP,hitMiss,responseTime,LocalDateTime.parse(timeZone,formatter),method,url,protocol,statusCode,trafficSize,referer,userAgent));
    }


}
